import { Row, Col, Upload, Grid, message, Button } from 'antd';
import wx from 'weixin-js-sdk';
import React, { useRef, useEffect, useState, useMemo } from 'react';
import { getFetch, formFetch } from '@/utils/doFetch';
import { PlusOutlined, EyeOutlined, DeleteOutlined, UploadOutlined } from '@ant-design/icons';
import styles from './index.less'

const { useBreakpoint } = Grid;

let FileUpload = ({ value, onChange, bordered, className, item, filelist, cfilelist, setVisible, setcururl }) => {
  const screens = useBreakpoint();
  useEffect(() => {
    getFetch({ url: "/wbn-api/wechat/signature", params: { url: document.URL } }).then(res => {
      if (res.code == 0) {
        wx.config({
          debug: false,
          appId: res.data.app_id,
          timestamp: res.data.timestamp,
          nonceStr: res.data.nonce_str,
          signature: res.data.signature,
          jsApiList: [
            "scanQRCode",
            "chooseImage",
            "getLocalImgData"
          ]
        })
        wx.ready(function () {
        })
        wx.error(function (err) {
        })
      }
    })
  }, []);

  function beforeUpload(file) {
    let size = window?.dataconfig?.limitSize ? window.dataconfig.serverURL : 20;
    const isJpgOrPng = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png';

    if (!isJpgOrPng && item.listType == 'img') {
      message.error('只能上传.jpg/.jpeg/.png图片!');
    }
    const isLt2M = file.size / 1024 / 1024 < size;
    if (!isLt2M) {
      message.error('图片大小须小于' + size + 'MB!');
    }
    if (item.listType == "img") {
      return isJpgOrPng && isLt2M;
    } else {
      return true
    }
  }

  const props = {
    name: "file",
    action: item.serverURL ? item.serverURL : window?.dataconfig?.serverURL,
    listType: item.listType == "img" ? "picture-card" : 'text',
    accept: item.listType == "img" ? ".jpg,.png,.jpeg," : "*",
    multiple: item.multiple ? item.multiple : false,
    beforeUpload: beforeUpload,
    fileList: filelist[item.name[0]],
    onChange(info) {
      let {
        file: { name, status, response },
        fileList,
      } = info;
      if (status == 'uploading') {
        cfilelist({
          ...filelist,
          [item.name[0]]: fileList
        })
      } else if (status == 'done' || status == 'removed') {
        cfilelist({
          ...filelist,
          [item.name[0]]: fileList.filter((it) => it.response && it.response.code == 0)
        })
        onChange(fileList.filter((it) => it.response && it.response.code == 0))
      } else if (status == 'error') {
        message.error(`${info.file.name} 上传失败`);
      } else {
        cfilelist({
          ...filelist,
          [item.name[0]]: fileList.filter((it) => it.response && it.response.code == 0)
        })
      }
    },
    onPreview(file) {
      if (file.response) {
        setcururl(file.response.data.origin_url)
      } else {
        setcururl(file.thumbUrl)
      }
      setVisible(true);
    }
  };

  const uploadBtn = item.listType == 'img' ? (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  ) : (
    <Button icon={<UploadOutlined />}>上传</Button>
  ),
    limit = item.limit ? item.limit : 1000;

  const dataURLtoFile = (dataurl, filename) => {
    let arr = dataurl.split(',');
    let mime = arr[0].match(/:(.*?);/)[1];
    let bstr = atob(arr[1]);
    let n = bstr.length;
    let u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    //转换成file对象
    return new File([u8arr], filename, { type: mime });
    //转换成成blob对象
    //return new Blob([u8arr],{type:mime});
  }

  let RenderImg = ({ cururl }) => {

    return <div className="hoverable" style={{ width: 104, height: 104, padding: 8, border: "1px solid #d9d9d9", margin: "0 8px 8px 0px" }}>
      <div style={{
        width: "100%",
        height: "100%",
        backgroundImage: `url(${cururl})`,
        backgroundSize: "contain",
        backgroundRepeat: "no-repeat",
        backgroundPosition: "center"
      }}>
        <div className="iconcon center">
          <EyeOutlined style={{ color: "#fff", fontSize: 20, marginRight: 10, textShadow: "2px 2px 2px #000" }} onClick={(e) => {
            e.stopPropagation()
            setVisible(true);
            setcururl(cururl)
          }} />
          <DeleteOutlined style={{ color: "#fff", fontSize: 20, textShadow: "2px 2px 2px #000" }} onClick={(e) => {
            e.stopPropagation()
            let fileList = filelist[item.name[0]];
            fileList = fileList.filter((it) => {
              let urls = it?.response?.data?.origin_url ? it?.response?.data?.origin_url : it?.origin_url
              return urls != cururl
            })
            cfilelist({
              ...filelist,
              [item.name[0]]: fileList
            })
            onChange(fileList);

          }} />
        </div>
      </div>
    </div>
  }

  return (
    <div className={styles.mainpiclist} style={{ display: "flex", justifyContent: "flex-start", alignItems: "center", minHeight: 114, minWidth: 114 }}>
      {//(screens.xs && !screens.sm)
        false ?
          <div>
            {
              filelist[item.name[0]] && filelist[item.name[0]].map((it, i) => {
                return <RenderImg cururl={it?.response?.data?.origin_url ? it?.response?.data?.origin_url : it?.origin_url} key={i} />
              })
            }
            {
              (filelist[item.name[0]] && filelist[item.name[0]].length > limit - 1) ?
                null :
                <div className="ant-upload ant-upload-select ant-upload-select-picture-card center" onClick={() => {
                  wx?.chooseImage({
                    count: limit > 9 ? 9 : limit, // 默认9
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                    success: function (res) {
                      var localIds = res.localIds;
                      localIds.map(it => {
                        wx.getLocalImgData({
                          localId: it, // 图片的localID
                          success: function (res) {
                            var localData = res.localData; // localData是图片的base64数据，可以用img标签显示
                            if (localData.substr(0, 5) != 'data:') {
                              localData = 'data:image;base64,' + localData;
                            }
                            let file = dataURLtoFile(localData, "images.jpg")
                            let params = new FormData();
                            params.append('file', file);
                            fetch("/wbn-api/file", {
                              method: 'POST',
                              body: params,
                            }).then(res => {
                              return res.json();
                            }).then(res => {
                              if (res.code != 0) {
                                message.error("只能上传.jpg/.jpeg/.png图片!")
                                return
                              }
                              let fileList = filelist[item.name[0]];
                              fileList.unshift(res.data);
                              cfilelist({
                                ...filelist,
                                [item.name[0]]: fileList
                              })
                              onChange(fileList);
                            })

                          }
                        });
                      })
                    }
                  });
                }}>
                  {uploadBtn}
                </div>
            }
          </div>


          : <Upload {...props} style={{ width: '100%' }}>
            {
              (filelist[item.name[0]] && filelist[item.name[0]].length > limit - 1) ? null : uploadBtn
            }
          </Upload>
      }

    </div>
  )
}

export default FileUpload
